{% extends 'base.html' %}
{% load static %}

{% block title %}{{ profile_user.nickname }} - 个人中心{% endblock %}

{% block extra_css %}
<style>
    .profile-header {
        background: var(--gradient-primary);
        color: white;
        padding: 3rem 0 5rem;
        margin-bottom: -3rem;
    }
    
    .profile-card {
        background: white;
        border-radius: 1rem;
        box-shadow: var(--shadow-lg);
        padding: 2rem;
        position: relative;
        z-index: 1;
    }
    
    .profile-avatar-container {
        text-align: center;
        margin-bottom: 1.5rem;
    }
    
    .profile-stats {
        display: flex;
        justify-content: space-around;
        padding: 1.5rem 0;
        border-top: 1px solid var(--border-color);
        border-bottom: 1px solid var(--border-color);
        margin: 1.5rem 0;
    }
    
    .profile-stat-item {
        text-align: center;
    }
    
    .profile-stat-value {
        font-size: 1.75rem;
        font-weight: 700;
        color: var(--primary-color);
        display: block;
    }
    
    .profile-stat-label {
        color: var(--gray-text);
        font-size: 0.9rem;
    }
    
    .tab-content-card {
        background: white;
        border-radius: 1rem;
        padding: 2rem;
        box-shadow: var(--shadow-md);
    }
</style>
{% endblock %}

{% block content %}
<!-- 个人资料头部 -->
<div class="profile-header">
    <div class="container">
        <h2 class="mb-0">个人中心</h2>
    </div>
</div>

<div class="container mb-5">
    <div class="row">
        <!-- 左侧用户信息 -->
        <div class="col-lg-4 mb-4">
            <div class="profile-card">
                <div class="profile-avatar-container">
                    <img src="{% if profile_user.avatar %}{{ profile_user.avatar.url }}{% else %}/static/img/default-avatar.png{% endif %}" 
                         alt="{{ profile_user.nickname }}" 
                         class="user-avatar-lg"
                         id="profileAvatar">
                    {% if user == profile_user %}
                    <button class="btn btn-sm btn-outline-primary mt-2" data-bs-toggle="modal" data-bs-target="#uploadAvatarModal">
                        <i class="fas fa-camera"></i> 更换头像
                    </button>
                    {% endif %}
                </div>
                
                <h4 class="text-center mb-2">{{ profile_user.nickname }}</h4>
                <p class="text-center text-muted mb-3">@{{ profile_user.username }}</p>
                
                {% if profile_user.signature %}
                <p class="text-center"><i class="fas fa-quote-left"></i> {{ profile_user.signature }} <i class="fas fa-quote-right"></i></p>
                {% endif %}
                
                <!-- 统计数据 -->
                <div class="profile-stats">
                    <div class="profile-stat-item">
                        <span class="profile-stat-value">{{ created_activities_count }}</span>
                        <span class="profile-stat-label">创建活动</span>
                    </div>
                    <div class="profile-stat-item">
                        <span class="profile-stat-value">{{ joined_activities_count }}</span>
                        <span class="profile-stat-label">参加活动</span>
                    </div>
                    <div class="profile-stat-item">
                        <span class="profile-stat-value">{{ profile_user.points }}</span>
                        <span class="profile-stat-label">积分</span>
                    </div>
                </div>
                
                <!-- 积分信息卡片 -->
                {% if user == profile_user %}
                <div class="card mb-3 border-0" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                    <div class="card-body text-white">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h6 class="mb-0"><i class="fas fa-coins"></i> 我的积分</h6>
                            <span class="badge bg-white text-primary">{{ profile_user.points }}</span>
                        </div>
                        <div class="row text-center mt-3">
                            <div class="col-6">
                                <div class="small">连续签到</div>
                                <div class="h5 mb-0">{{ consecutive_days }}天</div>
                            </div>
                            <div class="col-6">
                                <div class="small">本月签到</div>
                                <div class="h5 mb-0">{{ month_checkins }}次</div>
                            </div>
                        </div>
                        <a href="{% url 'points:checkin' %}" class="btn btn-light btn-sm mt-3 w-100">
                            <i class="fas fa-calendar-check"></i> 去签到
                        </a>
                    </div>
                </div>
                {% endif %}
                
                <!-- 操作按钮 -->
                <div class="d-grid gap-2 mt-3">
                    {% if user == profile_user %}
                        <a href="{% url 'users:settings' %}" class="btn btn-gradient-primary">
                            <i class="fas fa-cog"></i> 编辑资料
                        </a>
                    {% else %}
                        <button class="btn btn-gradient-primary" id="followBtn" data-user-id="{{ profile_user.id }}">
                            <i class="fas fa-user-plus"></i> <span id="followText">关注</span>
                        </button>
                        <button class="btn btn-outline-primary" onclick="sendMessage({{ profile_user.id }})">
                            <i class="fas fa-envelope"></i> 发送私信
                        </button>
                    {% endif %}
                </div>
                
                <!-- 兴趣标签 -->
                {% if interests_list %}
                <div class="mt-4">
                    <h6 class="mb-2"><i class="fas fa-heart text-danger"></i> 兴趣爱好</h6>
                    <div>
                        {% for interest in interests_list %}
                        <span class="tag-custom">{{ interest }}</span>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
                
                <!-- 注册时间 -->
                <div class="text-center mt-4 text-muted">
                    <small><i class="fas fa-calendar-alt"></i> 加入于 {{ profile_user.created_at|date:"Y年m月" }}</small>
                </div>
            </div>
        </div>
        
        <!-- 右侧内容区 -->
        <div class="col-lg-8">
            <!-- 标签页 -->
            <ul class="nav nav-tabs mb-4" id="profileTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button">
                        <i class="fas fa-chart-line"></i> 概览
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="activities-tab" data-bs-toggle="tab" data-bs-target="#activities" type="button">
                        <i class="fas fa-calendar-check"></i> 参与的活动
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="created-tab" data-bs-toggle="tab" data-bs-target="#created" type="button">
                        <i class="fas fa-plus-circle"></i> 创建的活动
                    </button>
                </li>
                {% if user == profile_user %}
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="points-tab" data-bs-toggle="tab" data-bs-target="#points" type="button">
                        <i class="fas fa-coins"></i> 积分明细
                    </button>
                </li>
                {% endif %}
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="following-tab" data-bs-toggle="tab" data-bs-target="#following" type="button">
                        <i class="fas fa-users"></i> 关注
                    </button>
                </li>
            </ul>
            
            <!-- 标签页内容 -->
            <div class="tab-content" id="profileTabContent">
                <!-- 概览标签页 -->
                <div class="tab-pane fade show active" id="overview">
                    <div class="tab-content-card">
                        <h5 class="mb-4"><i class="fas fa-chart-pie"></i> 数据统计</h5>
                        <div class="row g-3 mb-4">
                            <div class="col-md-3 col-6">
                                <div class="card border-primary">
                                    <div class="card-body text-center">
                                        <i class="fas fa-calendar-plus fa-2x text-primary mb-2"></i>
                                        <h4 class="mb-0">{{ created_activities_count }}</h4>
                                        <small class="text-muted">创建活动</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 col-6">
                                <div class="card border-success">
                                    <div class="card-body text-center">
                                        <i class="fas fa-calendar-check fa-2x text-success mb-2"></i>
                                        <h4 class="mb-0">{{ joined_activities_count }}</h4>
                                        <small class="text-muted">参加活动</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 col-6">
                                <div class="card border-warning">
                                    <div class="card-body text-center">
                                        <i class="fas fa-coins fa-2x text-warning mb-2"></i>
                                        <h4 class="mb-0">{{ profile_user.points }}</h4>
                                        <small class="text-muted">总积分</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 col-6">
                                <div class="card border-info">
                                    <div class="card-body text-center">
                                        <i class="fas fa-fire fa-2x text-danger mb-2"></i>
                                        <h4 class="mb-0">{{ consecutive_days }}</h4>
                                        <small class="text-muted">连续签到</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 最近动态 -->
                        <h5 class="mb-3"><i class="fas fa-history"></i> 最近活动</h5>
                        {% if recent_activities %}
                            {% for activity in recent_activities %}
                            <div class="card mb-2">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">
                                                <a href="/activities/{{ activity.id }}/" class="text-decoration-none">
                                                    {{ activity.title }}
                                                </a>
                                            </h6>
                                            <p class="text-muted small mb-2">
                                                <i class="fas fa-map-marker-alt"></i> {{ activity.location_name }}
                                                <span class="ms-2"><i class="fas fa-calendar"></i> {{ activity.start_time|date:"Y-m-d H:i" }}</span>
                                            </p>
                                        </div>
                                        <span class="badge bg-primary">{{ activity.activity_type.name }}</span>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-inbox fa-3x mb-3"></i>
                                <p>暂无活动记录</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 参与的活动 -->
                <div class="tab-pane fade" id="activities">
                    <div class="tab-content-card">
                        <div id="joinedActivitiesContainer">
                            <div class="text-center">
                                <div class="loader"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 创建的活动 -->
                <div class="tab-pane fade" id="created">
                    <div class="tab-content-card">
                        <div id="createdActivitiesContainer">
                            <div class="text-center">
                                <div class="loader"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 积分明细 -->
                {% if user == profile_user %}
                <div class="tab-pane fade" id="points">
                    <div class="tab-content-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="fas fa-coins text-warning"></i> 积分明细</h5>
                            <span class="badge bg-primary fs-6">当前积分: {{ profile_user.points }}</span>
                        </div>
                        
                        {% if recent_points %}
                            <div class="list-group">
                                {% for record in recent_points %}
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1">{{ record.get_type_display }}</h6>
                                            {% if record.description %}
                                            <p class="text-muted small mb-1">{{ record.description }}</p>
                                            {% endif %}
                                            <small class="text-muted">
                                                <i class="fas fa-clock"></i> {{ record.created_at|date:"Y-m-d H:i" }}
                                            </small>
                                        </div>
                                        <span class="fs-5 {% if record.points > 0 %}text-success{% else %}text-danger{% endif %}">
                                            {% if record.points > 0 %}+{% endif %}{{ record.points }}
                                        </span>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            <div class="text-center mt-3">
                                <a href="{% url 'points:records' %}" class="btn btn-outline-primary btn-sm">
                                    查看更多 <i class="fas fa-arrow-right"></i>
                                </a>
                            </div>
                        {% else %}
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-coins fa-3x mb-3"></i>
                                <p>暂无积分记录</p>
                                <a href="{% url 'points:checkin' %}" class="btn btn-primary">
                                    <i class="fas fa-calendar-check"></i> 去签到赚积分
                                </a>
                            </div>
                        {% endif %}
                    </div>
                </div>
                {% endif %}
                
                <!-- 关注列表 -->
                <div class="tab-pane fade" id="following">
                    <div class="tab-content-card">
                        <div id="followingContainer">
                            <div class="text-center">
                                <div class="loader"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 上传头像模态框 -->
{% if user == profile_user %}
<div class="modal fade" id="uploadAvatarModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">更换头像</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <img id="avatarPreview" src="{% if user.avatar %}{{ user.avatar.url }}{% else %}/static/img/default-avatar.png{% endif %}" class="user-avatar-lg">
                </div>
                <input type="file" class="form-control" id="avatarFile" accept="image/*">
                <div class="progress mt-3" style="display: none;" id="uploadProgress">
                    <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="uploadAvatarBtn">上传</button>
            </div>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script>
    const profileUserId = {{ profile_user.id }};
    const currentUserId = {% if user.is_authenticated %}{{ user.id }}{% else %}null{% endif %};
    
    // 加载参与的活动
    function loadJoinedActivities() {
        API.activities.getList({ participant: profileUserId, status: 'registered' })
            .then(response => {
                const container = document.getElementById('joinedActivitiesContainer');
                const activities = response.data.results || response.data;
                
                if (activities.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-calendar-times"></i>
                            <h3>还没有参与任何活动</h3>
                            <p>快去发现有趣的活动吧！</p>
                        </div>
                    `;
                } else {
                    container.innerHTML = activities.map(activity => renderActivityCard(activity)).join('');
                }
            })
            .catch(error => {
                console.error('加载活动失败:', error);
            });
    }
    
    // 加载创建的活动
    function loadCreatedActivities() {
        API.activities.getList({ creator: profileUserId })
            .then(response => {
                const container = document.getElementById('createdActivitiesContainer');
                const activities = response.data.results || response.data;
                
                if (activities.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-calendar-plus"></i>
                            <h3>还没有创建任何活动</h3>
                            <p>创建第一个活动，开启精彩生活！</p>
                        </div>
                    `;
                } else {
                    container.innerHTML = activities.map(activity => renderActivityCard(activity)).join('');
                }
            })
            .catch(error => {
                console.error('加载活动失败:', error);
            });
    }
    
    // 加载关注列表
    function loadFollowing() {
        API.users.getFollowing(profileUserId)
            .then(response => {
                const container = document.getElementById('followingContainer');
                const users = response.data.results || response.data;
                
                if (users.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-user-friends"></i>
                            <h3>还没有关注任何人</h3>
                        </div>
                    `;
                } else {
                    container.innerHTML = users.map(user => renderUserCard(user)).join('');
                }
            })
            .catch(error => {
                console.error('加载关注列表失败:', error);
            });
    }
    
    // 渲染活动卡片
    function renderActivityCard(activity) {
        return `
            <div class="mb-3">
                <a href="/activities/${activity.id}/" class="text-decoration-none">
                    <div class="card-custom">
                        <div class="card-body">
                            <h5 class="mb-2">${activity.title}</h5>
                            <p class="text-muted mb-2">${activity.description.substring(0, 100)}...</p>
                            <div class="d-flex justify-content-between">
                                <small class="text-muted">
                                    <i class="fas fa-calendar"></i> ${new Date(activity.start_time).toLocaleDateString()}
                                </small>
                                <small class="text-muted">
                                    <i class="fas fa-users"></i> ${activity.current_participants}/${activity.max_participants}
                                </small>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
        `;
    }
    
    // 渲染用户卡片
    function renderUserCard(user) {
        return `
            <div class="mb-3">
                <div class="card-custom">
                    <div class="card-body d-flex align-items-center">
                        <img src="${user.avatar || '/static/img/default-avatar.png'}" class="user-avatar me-3">
                        <div class="flex-grow-1">
                            <h6 class="mb-0">${user.nickname}</h6>
                            <small class="text-muted">@${user.username}</small>
                        </div>
                        <a href="/users/${user.id}/" class="btn btn-sm btn-outline-primary">查看</a>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 标签页切换事件
    document.getElementById('activities-tab').addEventListener('shown.bs.tab', loadJoinedActivities);
    document.getElementById('created-tab').addEventListener('shown.bs.tab', loadCreatedActivities);
    document.getElementById('following-tab').addEventListener('shown.bs.tab', loadFollowing);
    
    // 初始加载
    loadJoinedActivities();
    
    // 关注/取消关注
    {% if user != profile_user %}
    document.getElementById('followBtn')?.addEventListener('click', function() {
        const btn = this;
        const userId = this.dataset.userId;
        const text = document.getElementById('followText');
        const isFollowing = text.textContent === '已关注';
        
        const action = isFollowing ? API.users.unfollow(userId) : API.users.follow(userId);
        
        action.then(response => {
            if (isFollowing) {
                text.textContent = '关注';
                btn.innerHTML = '<i class="fas fa-user-plus"></i> <span id="followText">关注</span>';
                showSuccess('已取消关注');
            } else {
                text.textContent = '已关注';
                btn.innerHTML = '<i class="fas fa-user-check"></i> <span id="followText">已关注</span>';
                showSuccess('关注成功');
            }
        }).catch(error => {
            showError('操作失败，请重试');
        });
    });
    {% endif %}
    
    // 发送私信
    function sendMessage(userId) {
        window.location.href = `/users/messages/?to=${userId}`;
    }
    
    // 头像上传
    {% if user == profile_user %}
    document.getElementById('avatarFile')?.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                alert('请上传 JPG、PNG、GIF 或 WEBP 格式的图片');
                this.value = '';
                return;
            }
            
            // 验证文件大小（5MB）
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                this.value = '';
                return;
            }
            
            // 预览图片
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('avatarPreview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    
    document.getElementById('uploadAvatarBtn')?.addEventListener('click', function() {
        const fileInput = document.getElementById('avatarFile');
        const file = fileInput.files[0];
        
        if (!file) {
            alert('请选择图片');
            return;
        }
        
        const progress = document.getElementById('uploadProgress');
        const progressBar = progress.querySelector('.progress-bar');
        const uploadBtn = this;
        
        // 禁用按钮，显示进度条
        uploadBtn.disabled = true;
        uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
        progress.style.display = 'block';
        progressBar.style.width = '0%';
        
        // 创建FormData
        const formData = new FormData();
        formData.append('avatar', file);
        
        // 发送上传请求
        fetch('/users/api/upload-avatar/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                progressBar.style.width = '100%';
                
                // 更新页面上所有的头像显示
                const newAvatarUrl = data.data.avatar_url;
                
                // 更新个人中心头像
                const profileAvatar = document.getElementById('profileAvatar');
                if (profileAvatar) {
                    profileAvatar.src = newAvatarUrl;
                }
                
                // 更新导航栏头像（如果存在）
                const navAvatar = document.getElementById('navbarAvatar');
                if (navAvatar) {
                    navAvatar.src = newAvatarUrl;
                }
                
                // 更新预览头像
                document.getElementById('avatarPreview').src = newAvatarUrl;
                
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('uploadAvatarModal'));
                if (modal) {
                    modal.hide();
                }
                
                alert('头像更新成功！');
                
                // 重置按钮和进度条
                uploadBtn.disabled = false;
                uploadBtn.innerHTML = '上传';
                progress.style.display = 'none';
                fileInput.value = '';
            } else {
                throw new Error(data.message || '上传失败');
            }
        })
        .catch(error => {
            console.error('上传失败:', error);
            alert(error.message || '上传失败，请重试');
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = '上传';
            progress.style.display = 'none';
        });
    });
    
    // 获取CSRF token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    {% endif %}
</script>
{% endblock %}
